﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Utilities;

namespace ManageTicket.Ticket
{
    public partial class frmVoucher : frmBase
    {
        #region Contructor
        public frmVoucher(string voucher_no)
        {
            InitializeComponent();
            Voucher_No = voucher_no;
        }
        #endregion

        #region Variable
        ManageTicket.Library.Control.ExecuteControl exeCtrl;

        //permission
        bool bAdd = false;
        bool bEdit = false;
        bool bDelete = false;
        bool bCancel = false;
        bool bSave = false;
        bool bFunction = false;
        bool bView = false;
        bool bFind = false;
        bool bExport = false;
        bool bSendmail = false;
        bool bPrint = false;

        clsMethod4All objMethod = new clsMethod4All();
        ManageTicket.Library.Common.CommonFunction clsCommonFunc = new ManageTicket.Library.Common.CommonFunction();
        private Business.Voucher boVoucher = new Business.Voucher();
        private Business.VoucherHistory boVoucherHistory = new Business.VoucherHistory();
        private Business.Employee boEmployee = new Business.Employee();
        private Business.Customer boCustomer = new Business.Customer();
        private Business.Provider boProvider = new Business.Provider();
        private string Voucher_No = "";
        string sModel = ""; //Store AND or UPDATE status
        private const string ADD_MODEL = "ADD";
        private const string UPDATE_MODEL = "UPDATE";
        private bool isBuyVAT = false;
        private bool isSaleVAT = false;
        #endregion

        #region Event
        private void frmVoucher_Load(object sender, EventArgs e)
        {
            //execute control
            exeCtrl = new ManageTicket.Library.Control.ExecuteControl();
            exeCtrl.Dock = DockStyle.Fill;
            exeCtrl.lblDescription.Text = "Cập nhật vé";
            pnlExe.Controls.Add(exeCtrl);

            //permission
            clsCommonFunc.GetPermission(ref bAdd, ref bEdit, ref bDelete, ref bCancel, ref bSave, ref bFunction, ref bView, ref bFind, ref bExport, ref bSendmail, ref bPrint, frmMain.CurrentUser.UserId, "FORM_02");

            GetListProvider();
            GetListCustomer();

            //get code type
            clsCommonFunc.GetListCodeType(cboBuyCurrency, "CUR");
            clsCommonFunc.GetListCodeType(cboSaleCurrency, "CUR");
            clsCommonFunc.GetListCodeType(cboTransport, "TRANS");
            //clsCommonFunc.GetListCodeType(cboService, "SERV");
            GetListService();
            
            //set status
            LoadStatusOnce();

            if (Voucher_No != "")
            {
                DataObjects.Voucher oVou = boVoucher.GetObjectByPK(Voucher_No);
                if (oVou != null)
                {
                    sModel = UPDATE_MODEL;
                    FillData(oVou);
                    LoadStatus(false, true, true, true, true, true);
                    objMethod.en_dis_control(new Control[] { grpDetail }, new Control[] { });
                }
            }
            else
            {
                LoadStatus(true, false, false, false, false, false);
                objMethod.en_dis_control(new Control[] { }, new Control[] { grpDetail });
            }
        }

        private void txtEmployeeId_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                DataObjects.Employee oCus = boEmployee.GetObjectByPK(txtEmployeeId.Text);
                if (oCus != null)
                {
                    txtFullName.Text = oCus.LastName + " " + oCus.FirstName;
                    txtFullName.Focus();
                }
            }
        }

        private void dtpDateOfVoucher_ValueChanged(object sender, EventArgs e)
        {
            if (sModel == ADD_MODEL)
            {
                txtVoucherNo.Text = dtpDateOfVoucher.Value.ToString("yyyyMMdd") + clsCommonFunc.RuleNumber5(boVoucher.GetMaxID(dtpDateOfVoucher.Value.ToString("yyyyMMdd")) + 1);
                CalculateBuy();
                CalculateSale();
            }
        }

        //Buy
        private void cboProvider_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboProvider.SelectedIndex >= 0)
            {
                DataRowView drv = (DataRowView)cboProvider.SelectedItem;
                txtProviderPersonRepresent.Text = drv.Row.ItemArray[2].ToString();
            }
            else
            {
                txtProviderPersonRepresent.Text = "";
            }
        }

        private void cboBuyCurrency_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboBuyCurrency.DataSource != null)
            {
                if (cboBuyCurrency.SelectedValue.ToString().ToUpper() == "CUR_1")
                {
                    txtBuyExchange.Text = "1";
                    if (txtBuyTotal.Text != "")
                        CalculateBuy();
                }
            }
        }

        private void txtBuyTotal_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtBuyTotal.Text);
        }

        private void txtBuyTotal_Leave(object sender, EventArgs e)
        {
            CalculateBuy();
        }

        private void txtBuyVATPercent_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtBuyVATPercent.Text);
        }

        private void txtBuyVATPercent_Leave(object sender, EventArgs e)
        {
            CalculateBuy();
        }

        private void txtBuyVATPercent_TextChanged(object sender, EventArgs e)
        {
            isBuyVAT = false;
        }

        private void txtBuyVAT_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtBuyVAT.Text);
        }

        private void txtBuyVAT_Leave(object sender, EventArgs e)
        {
            CalculateBuy();
        }

        private void txtBuyVAT_TextChanged(object sender, EventArgs e)
        {
            isBuyVAT = true;
        }

        private void txtBuyExchange_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtBuyExchange.Text);
        }

        private void txtBuyExchange_Leave(object sender, EventArgs e)
        {
            CalculateBuy();
        }

        //Sale
        private void cboCustomer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboCustomer.SelectedIndex >= 0)
            {
                DataRowView drv = (DataRowView)cboCustomer.SelectedItem;
                txtCustomerPersonRepresent.Text = drv.Row.ItemArray[2].ToString();
            }
            else
            {
                txtCustomerPersonRepresent.Text = "";
            }
        }

        private void cboSaleCurrency_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboSaleCurrency.DataSource != null)
            {
                if (cboSaleCurrency.SelectedValue.ToString().ToUpper() == "CUR_1")
                {
                    txtSaleExchange.Text = "1";
                    if (txtSaleTotal.Text != "")
                        CalculateSale();
                }
            }
        }
        
        private void txtSaleTotal_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtSaleTotal.Text);
        }

        private void txtSaleTotal_Leave(object sender, EventArgs e)
        {
            CalculateSale();
        }

        private void txtSaleVATPercent_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtSaleVATPercent.Text);
        }

        private void txtSaleVATPercent_Leave(object sender, EventArgs e)
        {
            CalculateSale();
        }

        private void txtSaleVATPercent_TextChanged(object sender, EventArgs e)
        {
            isSaleVAT = false;
        }

        private void txtSaleVAT_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtSaleVAT.Text);
        }

        private void txtSaleVAT_Leave(object sender, EventArgs e)
        {
            CalculateSale();
        }

        private void txtSaleVAT_TextChanged(object sender, EventArgs e)
        {
            isSaleVAT = true;
        }
        
        private void txtSaleExchange_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtSaleExchange.Text);
        }

        private void txtSaleExchange_Leave(object sender, EventArgs e)
        {
            CalculateSale();
        }

        private void txtSaleCommission_KeyPress(object sender, KeyPressEventArgs e)
        {
            objMethod.InputNumber(e, txtSaleCommission.Text);
        }

        private void txtSaleCommission_Leave(object sender, EventArgs e)
        {
            txtSaleCommission.Text = objMethod.FormatCurency(txtSaleCommission.Text);
        }
        #endregion

        #region Method
        private void GetListService()
        {
            try
            {
                Business.CodeType boCodeType = new Business.CodeType();
                ArrayList arrCodeType = boCodeType.GetListCodeTypeByGroupNFreeField1("SERV", "VMB");              
                if (arrCodeType != null && arrCodeType.Count > 0)
                {
                    cboService.DataSource = arrCodeType;
                    cboService.ValueMember = "CodeTypeId";
                    cboService.DisplayMember = "CodeTypeName";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void GetListProvider()
        {
            try
            {
                ArrayList arr = boProvider.List();
                DataTable dataTable1 = new DataTable("Provider");
                dataTable1.Columns.Add("ProviderId", typeof(String));
                dataTable1.Columns.Add("ProviderName", typeof(String));
                dataTable1.Columns.Add("PersonRepresent", typeof(String));
                foreach (DataObjects.Provider oPro in arr)
                {
                    dataTable1.Rows.Add(new String[] { oPro.ProviderId, oPro.ProviderName, oPro.PersonContact });
                }
                cboProvider.DataSource = dataTable1;
                cboProvider.ValueMember = "ProviderName";
                cboProvider.DisplayMember = "ProviderId";
                cboProvider.SelectedIndex = -1;
                cboProvider.Text = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void GetListCustomer()
        {
            try
            {
                ArrayList arr = boCustomer.List();
                DataTable dataTable1 = new DataTable("Customer");
                dataTable1.Columns.Add("CustomerId", typeof(String));
                dataTable1.Columns.Add("CustomerName", typeof(String));
                dataTable1.Columns.Add("PersonRepresent", typeof(String));
                foreach (DataObjects.Customer oCus in arr)
                {
                    dataTable1.Rows.Add(new String[] { oCus.CustomerId, oCus.CustomerName, oCus.PersonContact });
                }
                cboCustomer.DataSource = dataTable1;
                cboCustomer.ValueMember = "CustomerName";
                cboCustomer.DisplayMember = "CustomerId";
                cboCustomer.SelectedIndex = -1;
                cboCustomer.Text = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadStatusOnce()
        {
            exeCtrl.btnEdit.Enabled = false;
            exeCtrl.btnView.Enabled = false;
            exeCtrl.btnFind.Enabled = false;
            exeCtrl.btnExport.Enabled = false;
            exeCtrl.btnSendmail.Enabled = false;

            exeCtrl.btnEdit.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnView.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnFind.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnExport.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnSendmail.ButtonColor = Color.FromArgb(171, 171, 171);

            exeCtrl.btnEdit.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnView.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnFind.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnExport.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnSendmail.ForeColor = Color.FromArgb(241, 244, 251);
        }

        private void LoadStatus(bool blAdd, bool blDelete, bool blCancel, bool blSave, bool blFunction, bool blPrint)
        {
            exeCtrl.btnAdd.Enabled = blAdd & bAdd;
            exeCtrl.btnDelete.Enabled = blDelete & bDelete;
            exeCtrl.btnCancel.Enabled = blCancel & bCancel;
            exeCtrl.btnSave.Enabled = blSave & bSave;
            exeCtrl.btnFunction.Enabled = blFunction & bFunction;
            exeCtrl.btnPrint.Enabled = blPrint & bPrint;

            exeCtrl.btnAdd.ButtonColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnDelete.ButtonColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnCancel.ButtonColor = exeCtrl.btnCancel.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnSave.ButtonColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnFunction.BackColor = exeCtrl.btnFunction.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnPrint.ButtonColor = exeCtrl.btnPrint.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);

            exeCtrl.btnAdd.ForeColor = exeCtrl.btnAdd.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnDelete.ForeColor = exeCtrl.btnDelete.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnCancel.ForeColor = exeCtrl.btnCancel.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnSave.ForeColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnFunction.ForeColor = exeCtrl.btnFunction.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnPrint.ForeColor = exeCtrl.btnPrint.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
        }

        private void ClearText()
        {
            objMethod.ClearText(new Control[] { txtVoucherNo, txtEmployeeId, txtFullName, txtCustomerNameDirect, txtTicketNo, cboTransport, cboService, txtTour, txtRemark,
                cboProvider, txtProviderName, txtProviderPersonRepresent, txtBuyTotal, txtBuyVATPercent, txtBuyVAT, txtBuySum, cboBuyCurrency, txtBuyExchange, txtBuySumVND,  
                cboCustomer, txtCustomerName, txtCustomerPersonRepresent, txtSaleTotal, txtSaleVATPercent, txtSaleVAT, txtSaleSum, cboSaleCurrency, txtSaleExchange, txtSaleSumVND, txtSaleCommission});
        }

        private void FillData(DataObjects.Voucher oVou)
        {
            try
            {
                txtVoucherNo.Text = oVou.VoucherNo;
                dtpDateOfVoucher.Value = oVou.DateOfVoucher.Value;
                txtEmployeeId.Text = oVou.EmployeeId;
                DataObjects.Employee oEmp = boEmployee.GetObjectByPK(oVou.EmployeeId);
                if (oEmp != null)
                    txtFullName.Text = oEmp.LastName + " " + oEmp.FirstName;
                txtCustomerNameDirect.Text = oVou.CustomerNameDirect;
                txtTicketNo.Text = oVou.TicketNo;
                if (oVou.TransportId != null && oVou.TransportId != "")
                    cboTransport.SelectedValue = oVou.TransportId;
                if (oVou.ServiceId != null && oVou.ServiceId != "")
                    cboService.SelectedValue = oVou.ServiceId;
                txtTour.Text = oVou.Tour;
                txtRemark.Text = oVou.Remark;

                //provider
                cboProvider.Text = oVou.ProviderId;
                txtProviderPersonRepresent.Text = oVou.ProviderPersonRepresent;
                DataObjects.Provider oPro = boProvider.GetObjectByPK(oVou.ProviderId);
                if (oPro != null)
                    txtProviderName.Text = oPro.ProviderName;
                txtBuyTotal.Text = objMethod.FormatCurency(oVou.BuyTotal.ToString());
                txtBuyVATPercent.Text = oVou.BuyVatPercent.ToString();
                txtBuyVAT.Text = objMethod.FormatCurency(oVou.BuyVat.ToString());
                txtBuySum.Text = objMethod.FormatCurency(oVou.BuySum.ToString());
                if (oVou.BuyCurrency != null && oVou.BuyCurrency != "")
                    cboBuyCurrency.SelectedValue = oVou.BuyCurrency;
                txtBuyExchange.Text = objMethod.FormatCurency(oVou.BuyExchange.ToString());
                txtBuySumVND.Text = objMethod.FormatCurency(oVou.BuySumVnd.ToString());

                //customer  
                cboCustomer.Text = oVou.CustomerId;
                txtCustomerPersonRepresent.Text = oVou.CustomerPersonRepresent;
                DataObjects.Customer oCus = boCustomer.GetObjectByPK(oVou.CustomerId);
                if (oCus != null)
                    txtCustomerName.Text = oCus.CustomerName;
                txtSaleTotal.Text = objMethod.FormatCurency(oVou.SaleTotal.ToString());
                txtSaleVATPercent.Text = oVou.SaleVatPercent.ToString();
                txtSaleVAT.Text = objMethod.FormatCurency(oVou.SaleVat.ToString());
                txtSaleSum.Text = objMethod.FormatCurency(oVou.SaleSum.ToString());
                if (oVou.SaleCurrency != null && oVou.SaleCurrency != "")
                    cboSaleCurrency.SelectedValue = oVou.SaleCurrency;
                txtSaleExchange.Text = objMethod.FormatCurency(oVou.SaleExchange.ToString());
                txtSaleSumVND.Text = objMethod.FormatCurency(oVou.SaleSumVnd.ToString());
                txtSaleCommission.Text = objMethod.FormatCurency(oVou.SaleCommission.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool CheckValid()
        {
            if (txtEmployeeId.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn nhân viên.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmployeeId.Focus();
                return false;
            }
            else
            {
                DataObjects.Employee oEmp = boEmployee.GetObjectByPK(txtEmployeeId.Text);
                if (oEmp == null)
                {
                    MessageBox.Show("Nhân viên không tồn tại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmployeeId.Focus();
                    return false;
                }
            }

            if (cboProvider.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn nhà cung cấp.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboProvider.Focus();
                return false;
            }


            if (cboCustomer.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng chọn khách hàng.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboCustomer.Focus();
                return false;
            }
            

            if (txtBuyExchange.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập tỷ giá mua.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtBuyExchange.Focus();
                return false;
            }
            else
            {
                if (double.Parse(txtBuyExchange.Text) < 1)
                {
                    MessageBox.Show("Vui lòng nhập tỷ giá mua.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtBuyExchange.Focus();
                    return false;
                }
            }

            if (txtSaleExchange.Text.Trim().Length == 0)
            {
                MessageBox.Show("Vui lòng nhập tỷ giá bán.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtSaleExchange.Focus();
                return false;
            }
            else
            {
                if (double.Parse(txtSaleExchange.Text) < 1)
                {
                    MessageBox.Show("Vui lòng nhập tỷ giá bán.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtSaleExchange.Focus();
                    return false;
                }
            }

            return true;
        }

        private void InsertVoucherHistory(DataObjects.Voucher oVou)
        {
            //insert
            DataObjects.VoucherHistory oVouHis = new DataObjects.VoucherHistory();
            oVouHis.VoucherNo = oVou.VoucherNo;
            oVouHis.DateCreate = oVou.DateOfVoucher;
            oVouHis.Status = "VSTATUS_1";
            oVouHis.Remark = oVou.Remark;
            oVouHis.UserId = frmMain.CurrentUser.UserId;
            oVouHis.DateInput = DateTime.Now;

            boVoucherHistory.Insert(oVouHis);
        }

        private void UpdateVoucherHistory(DataObjects.Voucher oVou)
        {
            ArrayList arr = boVoucherHistory.GetListByVoucherNoInvoiceNo(oVou.VoucherNo, "");
            foreach (DataObjects.VoucherHistory oVouHis in arr)
            {
                oVouHis.VoucherNo = oVou.VoucherNo;
                oVouHis.DateCreate = oVou.DateOfVoucher;
                oVouHis.Status = "VSTATUS_1";
                oVouHis.Remark = oVou.Remark;
                oVouHis.UserId = frmMain.CurrentUser.UserId;
                oVouHis.DateInput = DateTime.Now;

                //update
                boVoucherHistory.Update(oVouHis);
            }
        }

        private void CalculateBuy()
        {
            try
            {
                double total = 0;
                double vat_percent = 0;
                double vat = 0;
                double sum = 0;
                double exchange = 0;
                double sumvnd = 0;

                try { total = txtBuyTotal.Text != "" ? double.Parse(txtBuyTotal.Text) : 0; }
                catch { }
                if (isBuyVAT)
                {
                    try { vat = txtBuyVAT.Text != "" ? double.Parse(txtBuyVAT.Text) : 0; }
                    catch { }
                    try{ vat_percent = Math.Round(vat * 100 / total); }
                    catch { vat_percent = 0; }                   
                }
                else
                {
                    try { vat_percent = txtBuyVATPercent.Text != "" ? double.Parse(txtBuyVATPercent.Text) : 0; }
                    catch { }
                    vat = Math.Round(total * vat_percent / 100);
                }
                
                sum = total + vat;
                try
                {
                    if (cboBuyCurrency.SelectedValue.ToString().ToUpper() == "CUR_1")
                    {
                        exchange = 1;
                    }
                    else
                    {
                        exchange = txtBuyExchange.Text != "" ? double.Parse(txtBuyExchange.Text) : 0;
                    }
                }
                catch { }
                sumvnd = sum * exchange;

                //display
                txtBuyTotal.Text = objMethod.FormatCurency(total.ToString());
                txtBuyVATPercent.Text = objMethod.FormatCurency(vat_percent.ToString());
                txtBuyVAT.Text = objMethod.FormatCurency(vat.ToString());
                txtBuySum.Text = objMethod.FormatCurency(sum.ToString());
                txtBuyExchange.Text = objMethod.FormatCurency(exchange.ToString());
                txtBuySumVND.Text = objMethod.FormatCurency(sumvnd.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CalculateSale()
        {
            try
            {
                double total = 0;
                double vat_percent = 0;
                double vat = 0;
                double sum = 0;
                double exchange = 0;
                double sumvnd = 0;

                try { total = txtSaleTotal.Text != "" ? double.Parse(txtSaleTotal.Text) : 0; }
                catch { }
                if (isSaleVAT)
                {
                    try { vat = txtSaleVAT.Text != "" ? double.Parse(txtSaleVAT.Text) : 0; }
                    catch { }
                    try { vat_percent = Math.Round(vat * 100 / total); }
                    catch { vat_percent = 0; }
                }
                else
                {
                    try { vat_percent = txtSaleVATPercent.Text != "" ? double.Parse(txtSaleVATPercent.Text) : 0; }
                    catch { }
                    vat = Math.Round(total * vat_percent / 100);
                }

                sum = total + vat;
                try
                {
                    if (cboSaleCurrency.SelectedValue.ToString().ToUpper() == "CUR_1")
                    {
                        exchange = 1;
                    }
                    else
                    {
                        exchange = txtSaleExchange.Text != "" ? double.Parse(txtSaleExchange.Text) : 0;
                    }
                }
                catch { }
                sumvnd = sum * exchange;

                //display
                txtSaleTotal.Text = objMethod.FormatCurency(total.ToString());
                txtSaleVATPercent.Text = objMethod.FormatCurency(vat_percent.ToString());
                txtSaleVAT.Text = objMethod.FormatCurency(vat.ToString());
                txtSaleSum.Text = objMethod.FormatCurency(sum.ToString());
                txtSaleExchange.Text = objMethod.FormatCurency(exchange.ToString());
                txtSaleSumVND.Text = objMethod.FormatCurency(sumvnd.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool CheckIsExist(string voucher_no)
        {
            DataObjects.Voucher oVou = boVoucher.GetObjectByPK(voucher_no);
            if (oVou != null)
            {
                return true;
            }
            return false;
        }
        #endregion

        #region Execute
        public override void Add()
        {
            ClearText();
            sModel = ADD_MODEL;
            txtVoucherNo.Text = dtpDateOfVoucher.Value.ToString("yyyyMMdd") + clsCommonFunc.RuleNumber5(boVoucher.GetMaxID(dtpDateOfVoucher.Value.ToString("yyyyMMdd")) + 1);
            LoadStatus(false, false, true, true, false, false);
            objMethod.en_dis_control(new Control[] { grpDetail }, new Control[] { });
            txtEmployeeId.Text = frmMain.CurrentUser.EmployeeId;
            DataObjects.Employee oEmp = boEmployee.GetObjectByPK(txtEmployeeId.Text);
            if (oEmp != null)
                txtFullName.Text = oEmp.LastName + " " + oEmp.FirstName;
            dtpDateOfVoucher.Focus();
        }

        public override void Delete()
        {
            try
            {
                if (txtVoucherNo.Text == "")
                    return;

                if (MessageBox.Show("Bạn có thực sự muốn xóa?", "Aquarius", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    //Check Existing in table
                    //if (this.CheckExitToDelete(oDept.DEPT_CODE)) {
                    //    MessageBox.Show(".", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //    return;
                    //}

                    //delete relative
                    boVoucherHistory.DeleteByVoucherNo(txtVoucherNo.Text);

                    //delete
                    boVoucher.DeleteByPK(txtVoucherNo.Text);

                    MessageBox.Show("Xóa vé thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearText();
                    LoadStatus(true, false, false, false, false, false);
                    objMethod.en_dis_control(new Control[] { }, new Control[] { grpDetail });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public override void Cancel()
        {
            ClearText();
            sModel = "";
            LoadStatus(true, false, false, false, false, false);
            objMethod.en_dis_control(new Control[] { }, new Control[] { grpDetail });
        }

        public override void Save()
        {
            if (txtVoucherNo.Text == "")
            {
                return;
            }
            if (CheckValid())
            {
                try
                {
                    DataObjects.Voucher oVou = new DataObjects.Voucher();
                    oVou.VoucherNo = txtVoucherNo.Text;
                    oVou.DateOfVoucher = dtpDateOfVoucher.Value;
                    oVou.EmployeeId = txtEmployeeId.Text;
                    oVou.CustomerNameDirect = txtCustomerNameDirect.Text;
                    oVou.TicketNo = txtTicketNo.Text;
                    oVou.TransportId = cboTransport.SelectedValue != null ? cboTransport.SelectedValue.ToString() : "";
                    oVou.ServiceId = cboService.SelectedValue != null ? cboService.SelectedValue.ToString() : "";
                    oVou.Tour = txtTour.Text;
                    oVou.Remark = txtRemark.Text;
                    oVou.Status = "CURRENT";
                    //buy
                    oVou.ProviderId = cboProvider.Text;
                    oVou.ProviderPersonRepresent = txtProviderPersonRepresent.Text;
                    oVou.BuyTotal = txtBuyTotal.Text != "" ? double.Parse(txtBuyTotal.Text) : 0;
                    oVou.BuyVatPercent = txtBuyVATPercent.Text != "" ? double.Parse(txtBuyVATPercent.Text) : 0;
                    oVou.BuyVat = txtBuyVAT.Text != "" ? double.Parse(txtBuyVAT.Text) : 0;
                    oVou.BuySum = txtBuySum.Text != "" ? double.Parse(txtBuySum.Text) : 0;
                    oVou.BuyCurrency = cboBuyCurrency.SelectedValue != null ? cboBuyCurrency.SelectedValue.ToString() : "";
                    oVou.BuyExchange = txtBuyExchange.Text != "" ? double.Parse(txtBuyExchange.Text) : 0;
                    oVou.BuySumVnd = txtBuySumVND.Text != "" ? double.Parse(txtBuySumVND.Text) : 0;
                    //sale
                    oVou.CustomerId = cboCustomer.Text;
                    oVou.CustomerPersonRepresent = txtCustomerPersonRepresent.Text;
                    oVou.SaleTotal = txtSaleTotal.Text != "" ? double.Parse(txtSaleTotal.Text) : 0;
                    oVou.SaleVatPercent = txtSaleVATPercent.Text != "" ? double.Parse(txtSaleVATPercent.Text) : 0;
                    oVou.SaleVat = txtSaleVAT.Text != "" ? double.Parse(txtSaleVAT.Text) : 0;
                    oVou.SaleSum = txtSaleSum.Text != "" ? double.Parse(txtSaleSum.Text) : 0;
                    oVou.SaleCurrency = cboSaleCurrency.SelectedValue != null ? cboSaleCurrency.SelectedValue.ToString() : "";
                    oVou.SaleExchange = txtSaleExchange.Text != "" ? double.Parse(txtSaleExchange.Text) : 0;
                    oVou.SaleSumVnd = txtSaleSumVND.Text != "" ? double.Parse(txtSaleSumVND.Text) : 0;
                    oVou.SaleCommission = txtSaleCommission.Text != "" ? double.Parse(txtSaleCommission.Text) : 0;

                    if (sModel == ADD_MODEL)
                    {
                        if (CheckIsExist(oVou.VoucherNo))
                        {
                            MessageBox.Show("Số phiếu đã tồn tại.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            txtVoucherNo.Focus();
                            return;
                        }
                        boVoucher.Insert(oVou);
                        InsertVoucherHistory(oVou);
                    }
                    else if (sModel == UPDATE_MODEL)
                    {
                        boVoucher.Update(oVou);
                        UpdateVoucherHistory(oVou);
                    }

                    MessageBox.Show("Cập nhật vé thành công.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadStatus(true, true, false, false, true, true);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + Environment.NewLine + "Không thể cập nhật vé.", "Aquarius Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        public override void Print()
        {
            if (txtVoucherNo.Text.Trim() != "")
            {
                frmPrintTicket frm = new frmPrintTicket(txtVoucherNo.Text);
                frm.ShowDialog();
            }
        }
        #endregion

        

        
    }
}
